import React, { useCallback } from 'react'
import FileUpload from '@/components/FileUpload'
import { uploadFileToServer } from '@/apis/file'
import { battleSave } from '@/apis/battle'
import { nowMinute } from '@/utils'

export default function UploadArea({ onSuccess }: { onSuccess?: () => void }) {
  // 处理文件上传和业务逻辑
  const handleUpload = useCallback(
    async (files: File[]) => {
      if (files.length === 0) return
      if (files.length > 1) {
        // 多文件合并处理
        const wasmModulePromise = import('@/lib/pkg/example_wasm')
        const { default: init, merge_files } = await wasmModulePromise
        await init()
        const fileArray = await Promise.all(
          files.map((file) => file.arrayBuffer())
        )
        const fileBuffers = fileArray.map((buffer) => new Uint8Array(buffer))
        const mergedText = merge_files(fileBuffers)
        const mergedFile = new File(
          [mergedText.toString()],
          '聚合战斗信息' + nowMinute() + '.txt',
          { type: 'text/plain' }
        )
        const res = await uploadFileToServer(mergedFile)
        if (res) {
          await battleSave({
            data: {
              id: res.id,
              title: res.name,
              path: res.path,
              status: 1
            }
          })
        }
        if (onSuccess) onSuccess()
      } else {
        // 单文件处理
        for (let i = 0; i < files.length; i++) {
          const file = files[i]
          const res = await uploadFileToServer(file)
          if (res) {
            await battleSave({
              data: {
                id: res.id,
                title: res.name,
                path: res.path,
                status: 1
              }
            })
          }
        }
        if (onSuccess) onSuccess()
      }
    },
    [onSuccess]
  )

  return (
    <FileUpload
      onUpload={handleUpload}
      accept=".txt"
      multiple
      label="拖拽战斗文件到此处，或 点击上传"
      description="支持多文件自动合并上传"
    />
  )
}
